import { useStore } from "vuex";
// @ts-ignore
import * as VueRouter from "vue-router";


// import.meta.glob() 直接引入所有的模块 Vite 独有的功能
const modules = import.meta.glob('./modules/*.ts', { eager: true });

const routeModuleList:any=[]

console.log('modules',modules)
// 加入到路由集合中
Object.keys(modules).forEach((key) => {
    // @ts-ignore
    const mod = modules[key].default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    console.log('modList',modList)
    routeModuleList.push(...modList);
});



console.log('routeModuleList',routeModuleList)
const router: any = VueRouter.createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: VueRouter.createWebHashHistory(),
    routes: routeModuleList,
});

// 路由权限  beforeResolve
// @ts-ignore
router.beforeResolve(async (to: any, from: any, next: any) => {

    console.log('to',to)
    console.log('from',from)


    console.log('history state',history.state)
    console.log('location.href',location.href.split('#')[0])
    console.log('localStorage.getItem current_path',localStorage.getItem('current_path'))

    if(localStorage.getItem('current_path')!==null&&location.href.split('#')[0]!==localStorage.getItem('current_path')){
        console.log('clear__________')
        localStorage.clear()
    }
    const store=useStore()
    console.log('store.state.user.isLogin',store.state.user.isLogin)
    // 登录
    if (to.name === "login" || to.name === "register"||to.name === "verify"||store.state.user.isLogin) {
        //  localStorage.setItem('current_path',location.href.split('#')[0])
        console.warn("login|register");
        return next();
    }
    // 用户信息
    const token: any =
        window.localStorage.getItem("userInfoPermissionToken");
    const params = {token};
    if (params.token) {
        try{

            const {data}=await store.dispatch("user/loginUser", params);

            if (data?.code===200) {
                localStorage.setItem('current_path',location.href.split('#')[0])
                return next();
            }
        }
        catch(r){
            console.log('r',r)
            return next({ name: "login" });
        }
    }
    // 返回登录
    return next({ name: "login" });
});
export default router;
